/*
 * @Author: Theoton
 * @Date: 2018-03-27 10:21:46
 * @Last Modified by: lyuan2018
 * @Last Modified time: 2020-08-13 13:27:23
 */
import React from 'react';
import { toJS } from 'mobx';
import { inject, observer } from 'mobx-react';
import { Spin, Button, message } from 'antd';
import {
  WeaDialog,
  WeaErrorPage,
  WeaTools,
  WeaFormItem,
  WeaTagGroup,
  WeaError,
  WeaInput,
  WeaMoreButton,
  WeaLocaleProvider,
  WeaBrowser,
  WeaCheckbox,
} from 'ecCom';

import { emailValidate } from '../../util/index';

const getLabel = WeaLocaleProvider.getLabel;
const MAILPAGENAME = 'CREATEGROUP';

const { tryCatch } = WeaTools;

const store = ['routing', 'emailNewStore', 'emailCreateGroupStore'];

@tryCatch(
  React,
  props => (
    <WeaErrorPage
      ecId={`${
        (this && this.props && this.props.ecId) || ''
      }_WeaErrorPage@lqpi7z`}
      msg={
        props.error ||
        getLabel(186, '对不起，该页面异常，请联系管理员！', 'error')
      }
    />
  ),
  { error: '' },
)
@inject(...store)
@observer
class CreateGroup extends React.Component {
  static displayName = 'CreateGroup';
  static defaultProps = {
    prefixCls: 'wea-email-new-cgroup',
  };
  constructor(props) {
    super(props);
    this.isInstanceMounted = false;
  }
  componentDidMount() {
    this.isInstanceMounted = true;
  }
  componentWillUnmount() {
    this.isInstanceMounted = false;
  }
  validate(params) {
    let canSubmit = true;
    if (params.groupName.trim() === '') {
      this.refs.name.showError();
      canSubmit = false;
    }
    if (params.ids === '' || params.emails === '') {
      this.refs.list.showError();
      canSubmit = false;
    }
    if (params.emails && params.emails !== '') {
      params.emails.split(',').forEach((item) => {
        if (emailValidate(item)) {
          message.error(getLabel('18779', '邮件地址格式错误'));
          canSubmit = false;
        }
      });
    }
    return canSubmit;
  }
  save = async () => {
    const {
      emailCreateGroupStore,
      isInternal,
      onOk,
      emailNewStore: { getContactsTree, getHrmGroup },
      emailCreateGroupStore: { list, groupName, clear, updateMailAddress },
    } = this.props;
    let params = {
      groupName,
      [isInternal === 1 ? 'ids' : 'emails']: `${list.map((l) => {
        if (isInternal === 1) {
          return l.type == 'resource' ? l.id : '';
        }
        return l.id;
      })}`,
      emailnames: isInternal
        ? JSON.stringify([])
        : JSON.stringify(list.map(v => this.getNameAndAddress(v.name))),
      updateMailAddress,
    };
    if (this.validate(params)) {
      const fn = isInternal ? 'addInnerGroup' : 'addContactGroup';
      const res = await emailCreateGroupStore[fn](params);
      if (res.status === '1') {
        clear();
        isInternal ? getHrmGroup() : getContactsTree();
        typeof onOk === 'function' && onOk();
      }
    }
  };

  getNameAndAddress = (value) => {
    let address = value.match(/<(.*?)>/g);
    address =
      address && address.length > 0
        ? address[address.length - 1].replace(/[<>\s]/g, '').trim()
        : value;
    let username = value.match(/^.*</);
    username = username ? username[0].replace(/<$/, '').trim() : '';
    return {
      mailusername: username,
      mailaddress: address,
    };
  };

  getContent() {
    const {
      emailCreateGroupStore: { groupName, setState, updateMailAddress },
      isInternal,
    } = this.props;
    let {
      emailCreateGroupStore: { list },
    } = this.props;
    list = !isInternal
      ? toJS(list)
      : toJS(list).filter(v => v.type === 'resource');
    let items = [
      <WeaFormItem
        ecId={`${
          (this && this.props && this.props.ecId) || ''
        }_WeaFormItem@iwpp0z@${MAILPAGENAME}name`}
        label={getLabel(81303, '输入组名称')}
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 18 }}
      >
        <WeaError
          ecId={`${
            (this && this.props && this.props.ecId) || ''
          }_WeaError@1jmom4@${MAILPAGENAME}name`}
          tipPosition="bottom"
          error={getLabel(384350, '组名不能为空')}
          ref="name"
        >
          <WeaInput
            ecId={`${
              (this && this.props && this.props.ecId) || ''
            }_WeaInput@h3s43g@${MAILPAGENAME}name`}
            value={groupName}
            viewAttr="3"
            onChange={v => setState({ groupName: v })}
          />
        </WeaError>
      </WeaFormItem>,
      <WeaFormItem
        ecId={`${
          (this && this.props && this.props.ecId) || ''
        }_WeaFormItem@6i1q5z@${MAILPAGENAME}member`}
        label={getLabel(384349, '分组成员')}
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 18 }}
      >
        <WeaError
          ecId={`${
            (this && this.props && this.props.ecId) || ''
          }_WeaError@tyq0x7@${MAILPAGENAME}member`}
          tipPosition="bottom"
          error={getLabel(384348, '分组成员不能为空')}
          ref="list"
        >
          {!isInternal && (
            <WeaTagGroup
              ecId={`${
                (this && this.props && this.props.ecId) || ''
              }_WeaTagGroup@av5gfo@${MAILPAGENAME}member`}
              type={'emailOuterInput'}
              hasBrowser={!!isInternal}
              isTag={!isInternal}
              datas={toJS(list)}
              isShowGroup={true}
              validate={v => (isInternal ? false : emailValidate(v))}
              validateAll={true}
              onChange={v => setState({ list: v })}
            />
          )}
          {isInternal ? (
            <WeaBrowser
              ecId={`${
                (this && this.props && this.props.ecId) || ''
              }_WeaBrowser@hddkxf@${MAILPAGENAME}member`}
              type={17}
              inputStyle={{ maxWidth: 300 }}
              textDecoration
              onChange={(ids, names, v) => {
                if (ids == '') {
                  setState({ list: v });
                  this.refs.list.showError();
                } else {
                  setState({ list: v });
                }
              }}
              replaceDatas={toJS(list)}
              isSingle={false}
              viewAttr="3"
            />
          ) : null}
        </WeaError>
      </WeaFormItem>,
    ];
    if (!isInternal) {
      items.push(
        <WeaFormItem
          ecId={`${
            (this && this.props && this.props.ecId) || ''
          }_WeaFormItem@g7h2tr@${MAILPAGENAME}updatemail`}
          label={getLabel(521909, '更新联系人昵称')}
          labelCol={{ span: 6 }}
          wrapperCol={{ span: 18 }}
        >
          <WeaCheckbox
            ecId={`${
              (this && this.props && this.props.ecId) || ''
            }_WeaCheckbox@ne3ytk@${MAILPAGENAME}updatemail`}
            id="updateMailAddress"
            value={updateMailAddress}
            onChange={(v) => {
              setState({ updateMailAddress: v });
            }}
            helpfulTip={getLabel(
              521907,
              '勾选后，会同步更新联系人中邮件地址已存在的联系人昵称',
            )}
          />
        </WeaFormItem>,
      );
    }

    return items;
  }
  render() {
    const {
      emailCreateGroupStore: { visible, loading, clear },
      prefixCls,
      isInternal,
    } = this.props;
    return (
      <WeaDialog
        ecId={`${
          (this && this.props && this.props.ecId) || ''
        }_WeaDialog@8epz3o`}
        className={`${prefixCls}-dialog`}
        icon="icon-coms-email"
        iconBgcolor="#a0b0ba"
        title={
          isInternal == 1
            ? getLabel(384347, '创建常用组')
            : getLabel(129761, '创建联系人组')
        }
        visible={visible}
        style={{ width: 520 }}
        onCancel={() => clear()}
        maskClosable={false}
        buttons={[
          <Button
            ecId={`${
              (this && this.props && this.props.ecId) || ''
            }_Button@zgl8ep@${MAILPAGENAME}save`}
            type="primary"
            onClick={this.save}
          >
            {getLabel(30986, '保存')}
          </Button>,
          <WeaMoreButton
            ecId={`${
              (this && this.props && this.props.ecId) || ''
            }_WeaMoreButton@d6yhs8@${MAILPAGENAME}more`}
            datas={[]}
          />,
        ]}
      >
        <Spin
          ecId={`${(this && this.props && this.props.ecId) || ''}_Spin@ev109d`}
          spinning={loading}
        >
          <div className={`${prefixCls}-content`}>{this.getContent()}</div>
        </Spin>
      </WeaDialog>
    );
  }
}

export default CreateGroup;
